﻿using AutoMapper;
using ProjectManageSystemApi.DbEntity;
using ProjectManageSystemApi.Models;
using ProjectManageSystemApi.Models.PurchaseOrderModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProjectManageSystemApi.Services.Impl
{
    public class PurchaseOrderServices : ServicesBase, IPurchaseOrderServices
    {
        readonly Config _config;
        public PurchaseOrderServices(IFreeSql fsql, IMapper mapper, Config config) : base(fsql, mapper)
        {
            _config = config;
        }
        public bool Create(AddPurchaseOrderDto dto, long userId)
        {
            var data = _mapper.Map<PurchaseOrder>(dto);
            data.CreateTime = DateTime.Now;
            data.CreateUser = userId;
            return _fsql.Insert<PurchaseOrder>(data).ExecuteIdentity() > 0;
        }

        public PageVo<List<PurchaseOrderDto>> Get(PageBo<PurchaseOrderParams> pagebo)
        {
            var data = _fsql.Select<PurchaseOrder>()
                .Include(x => x.CreateUserInfo)
                .Include(x => x.BuyerUserInfo)
                .WhereIf(pagebo.Param.StartTime.HasValue && pagebo.Param.EndTime.HasValue && pagebo.Param.StartTime.Value > _config.MinDate && pagebo.Param.EndTime.Value > _config.MinDate, 
                    x=> x.CreateTime >= pagebo.Param.StartTime && x.CreateTime < pagebo.Param.EndTime)
                .WhereIf(pagebo.Param.Buyer.HasValue && pagebo.Param.Buyer > 0,
                    x => x.Buyer == pagebo.Param.Buyer);
            var result = new PageVo<List<PurchaseOrderDto>>()
            {
                Page = pagebo.Page,
                Size = pagebo.Size,
            };
            result.Total = data.Count();
            data = data.Page(pagebo.Page, pagebo.Size);
            result.Datas = _mapper.Map<List<PurchaseOrderDto>>(data.ToList());
            return result;
        }
    }
}
